<?php
namespace app\api\controller\audience;
use app\api\controller\common\ApiBase;
use Think\Db;
use PHPExcel_IOFactory;
use app\api\controller\common\SmsDemo;
use app\api\model\Admin as AdminModel;
use app\api\controller\contractmanage\Commonxc;
// Controller  ApiBase （dengl）
class Estimate extends ApiBase
{
    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
    }

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName='';
        if($result){
            $tabName=$result['create_person_table'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    public function getTabName1($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    /**
     * 预登记观众列表  0527
     * @return \think\response\Json|void
     *  // zh_20200528fmr
     */

    public function index(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $exhibition_id =$this->request->param('exhibition_id');
        $status=$this->request->param('status')==''?1:$this->request->param('status');
        $examine_type=$this->request->param('examine_type');
        $is_push=$this->request->param('is_push');
        $is_beforehand=$this->request->param('is_beforehand');
        $phone=$this->request->param('phone');
        $order_status=$this->request->param('order_status');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $tabName1=$this->getTabName1($exhibition_id);
        $tabName='crm_'.$tabName;
        //back字段 0代表正常 1代表退回数据
        //status前端传入1代表 全部 2代表 未联系 3代表 已联系
        $param=" ";
        if($status == 2){
            $param.=" and p.status=4";
        }else if($status == 3){
            $param.=" and p.status!=4";
        }else if($status == 4){
            $param.=" and p.group_invitation_type = 2";
        }else if($status == 4)

        if($is_beforehand == 1){
            $param.=" and p.is_beforehand=1";
        }else if($is_beforehand == 2){
            $param.=" and p.is_beforehand=2";
        }

        if($order_status == 1){
            $param.=" and p.id in (select user_id from crm_company_user_order where exhibition_id=".$exhibition_id." and status=1) ";
        }else if($order_status == 2){
            $param.=" and p.id not in (select user_id from crm_company_user_order where exhibition_id=".$exhibition_id." and status=1) ";
        }

        if($phone){
            $param.=" and p.mobile_person  like '%$phone%' ";
        }


        if($examine_type == 2){
            $param.=" and (p.examine_type=0 or p.examine_type=2)";
        }else if($examine_type == 3){
            $param.=" and p.examine_type=1";
        }else if($examine_type == 4){
            $param.=" and p.examine_type=3";
        }

        if($is_push == 2){
            $param.=" and p.is_push=1 ";
        }else if($is_push == 3){
            $param.=" and p.is_push=0 AND p.examine_type=1 AND p.id_side<>'' ";
        }
        $keyword =input('keyword');
        if (!empty($keyword)) {
            $param.=" and (p.company_name like '%$keyword%' or p.name_cn like '%$keyword%')";
        }
        $sql2="select p.id,p.is_major,p.status,p.label,p.is_beforehand,p.id_positive,p.is_cart,p.contact_time,p.positions_cn,p.department_cn,p.contact_person_name,p.registration_no,p.contact_person,p.examine_type,p.is_beforehand,p.create_time,p.person_id,p.id_positive,p.id_side,p.question,p.mobile_person,p.data_from,p.company_name,p.area_city,p.info_level,p.name_cn,p.company_address,p.link,p.contact,p.category_id,p.second_category_id,p.back,p.parent_id,p.company_parent_id,p.channel_id,p.is_push,u.name_cn as parent_name,q.title,z.company_name as parent_company_name,aq.title as active_qu_title,aq.id as active_qu_id,o.status as order_status";
        $sql2.=" from ".$tabName." as p ";
        $sql2.=" left join crm_company_user as u on u.id=p.parent_id";
        $sql2.=" left join crm_".$tabName1." as z on z.id=p.company_parent_id";
        $sql2.=" left join crm_zsqudao as q on q.id=p.channel_id and p.is_beforehand=1";
        $sql2.=" left join crm_active_zsqudao as aq on aq.id=p.channel_id and p.is_beforehand=2";
        $sql2.=" left join crm_company_user_order as o on o.user_id=p.id and o.exhibition_id=".$exhibition_id;
        $sql2.=" where 1=1 $param";
        $sql2.=" order by p.id desc";
        $sql2.=" limit ".($page-1)*$pagesize.",$pagesize";
        $list=Db::query($sql2);
        $sql21=" select count(p.id) as count1 ";
        $sql21.=" from ".$tabName." as p where 1=1 $param ";
        $total1=Db::query($sql21);
        $total=$total1[0]['count1']; //st
        foreach ($list as &$v){
            $label=db('company_user_label')->where(['person_id'=>$v['person_id'],'label_type'=>array('gt',1)])->select();
            $v['label_list']=$label;
            $v['mobile_person']=$v['mobile_person']?substr_replace($v['mobile_person'], '****', 3, 4):'';
        }
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    //审核
    public function examine(){
        $exhibition_id =$this->request->param('exhibition_id');
        $ids=$this->request->param('ids');
        $types=$this->request->param('types');
        $exhibition=db('exhibition')->where(['id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会数据有误','data'=>'']);
        }
        if(empty($ids)){
            return json(['code'=>0,'msg'=>'观众数据有误','data'=>'']);
        }

        $tabName=$this->getTabName($exhibition_id);
        if($exhibition['is_open'] == 1){
            $res=db($tabName)->where(['id'=>['in',$ids]])->update(['examine_type'=>$types]);
            if(!$res){
                return json(['code'=>0,'msg'=>'操作失败']);
            }
            return json(['code'=>1,'msg'=>'操作成功']);
        }
        $sql="select id,is_cart,name_cn,name_en,email,person_id,mobile_person,examine_type FROM crm_".$tabName;
        $sql.=" where id in (".$ids.") and examine_type!=".$types;
        $list=Db::query($sql);
        $phone=array();$smsData=array();
        foreach ($list as &$v){
            if($v['mobile_person']){
                $phone[]=$v['mobile_person'];
                $smsData[]=array('is_cart'=>$v['is_cart'],'userName'=>($v['name_cn']?$v['name_cn']:($v['name_en']?$v['name_en']:'预登记观众')));
            }
        }
        unset($v);
        if(!empty($phone)){
            $sms_type=$types==1?2:3;
//            $smsEmil=$this->smsEmail($phone,$types,$smsData,$exhibition_id,$exBusArr);
            $phone_tmp=db('email_sms')->where(['type'=>0,'sms_type'=>$sms_type,'exhibition_id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$phone_tmp){
                return json(['code'=>0,'msg'=>'短信模板错误']);
            }
            $sms_autograph=array();
            foreach ($phone as &$vv){
                $sms_autograph[]=$phone_tmp['sms_autograph'];
            }
            unset($vv);
            $SmsDemo=new SmsDemo();
            $smsEmil = $SmsDemo->sendBatchSms($phone,$sms_autograph,$phone_tmp['sms_code'],$smsData);
            if(is_object($smsEmil) && $smsEmil->Code== 'OK'){
                db($tabName)->where(['id'=>['in',$ids]])->update(['examine_type'=>$types]);
                return json(['code'=>1,'msg'=>'操作成功，短信发送成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作成功，短信发送失败']);
            }
        }else{
            return json(['code'=>0,'msg'=>'操作失败']);
        }
    }


    public function smsEmail(){
        $exhibition_id =$this->request->param('exhibition_id');
        $ids=$this->request->param('ids');
        $types=$this->request->param('types');
        if(empty($ids)){
            return json(['code'=>0,'msg'=>'观众数据有误','data'=>'']);
        }

        if($types == 1){
            $exhibition=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $email=db('email_sms')->where(['type'=>1,'exhibition_id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$email){
                return json(['code'=>0,'msg'=>'邮件模板信息错误']);
            }
            if(is_array($email) && is_array($exhibition)){
                //处理
                $stime=strtotime($exhibition['starttime']);
                $etime=strtotime($exhibition['endtime']);
                $datearr = [];
                $timeArr=['9:00 - 17:00','9:00 - 17:00','9:00 - 15:00'];
                $num=0;
                while ($stime <= $etime) {
                    $a=date("Y年m月d日", $stime);
                    $datearr[] = $a.' '.$timeArr[$num];//得到dataarr的日期数组。
                    $stime = $stime + 86400;
                    $num++;
                }
                $exhibition['datearr']=$datearr;
            }

            $sql="select z.id,z.is_cart,z.name_cn,z.name_en,z.email,z.person_id,z.mobile_person,z.examine_type,l.imgebase,l.exhibition_id FROM crm_".$tabName." as z ";
            $sql.=" left join crm_poster_log as l on l.id_zs=z.person_id ";
            $sql.=" where l.exhibition_id=".$exhibition_id." and z.id in (".$ids.") and z.examine_type<>".$types;
            $list=Db::query($sql);
            $ex_bus_user=array();
            foreach ($list as &$v){
                if($v['email']) {
                    $ex_bus_user[] = ['name_cn' => $v['name_cn'], 'name_en' => $v['name_en'], 'email' => $v['email'], 'is_cart' => $v['is_cart'], 'imgebase' => $v['imgebase']];
                }
            }
            if(!empty($ex_bus_user)){
                $com1=new Commonxc();
                $res=$com1->sendmailtpces($email,$exhibition,$ex_bus_user,'1');
                if(!$res){
                    return json(['code'=>0,'msg'=>'邮件发送失败']);
                }
                return json(['code'=>1,'msg'=>'邮件发送成功']);
            }else{
                return json(['code'=>0,'msg'=>'邮件发送失败,缺少邮件编号']);
            }

        }
    }

    // 导出  stj ce
    public function export()
    {
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $exhibition_id =$this->request->param('exhibition_id');
        $status=$this->request->param('status')==''?1:$this->request->param('status');
        $examine_type=$this->request->param('examine_type');
        $excelType=$this->request->param('excelType');
        $is_push=$this->request->param('is_push');
        $is_beforehand=$this->request->param('is_beforehand');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $tabNames=$this->getTabName($exhibition_id);
        $tabName1=$this->getTabName1($exhibition_id);
        $tabName='crm_'.$tabNames;
        $param=" ";
        if($status == 2){
            $param.=" and p.status=4";
        }else if($status == 3){
            $param.=" and p.status!=4";
        }else if($status == 4){
            $param.=" and p.group_invitation_type = 2";
        }
        if($status == 2){
            $param.=" and p.status=4";
        }else if($status == 3){
            $param.=" and p.status!=4";
        }else if($status == 4){
            $param.=" and p.group_invitation_type = 2";
        }

        if($is_beforehand == 1){
            $param.=" and p.is_beforehand=1";
        }else if($is_beforehand == 2){
            $param.=" and p.is_beforehand=2";
        }

        if($examine_type == 2){
            $param.=" and (p.examine_type=0 or p.examine_type=2)";
        }else if($examine_type == 3){
            $param.=" and p.examine_type=1";
        }else if($examine_type == 4){
            $param.=" and p.examine_type=3";
        }

        if($is_push == 2){
            $param.=" and p.is_push=1 ";
        }else if($is_push == 3){
            $param.=" and p.is_push=0 AND p.examine_type=1 AND p.id_side IS NOT NULL";
        }
        $pageSize=$excelType == 2?3000:5000;
        $sql2="select p.id,p.is_major,p.is_push,p.group_invitation_type,p.status,p.is_beforehand,p.id_positive,p.name_cn,p.name_en,p.company_name,p.mobile_person,p.id_side,p.email,p.country,p.province,p.area,p.company_name_en,p.examine_type,
        p.area_city,p.industrys,p.department_cn,p.positions_cn,from_unixtime(p.create_time,'%Y-%m-%d %H:%i:%s') as create_time,p.is_cart,
        q.title,l.label as label_titles,
        u.name_cn as parent_name,o.status as order_status,
        z.company_name as company_name_parent";
        if($excelType == 2){
            $sql2.=",p.question,p.question1";
        }
        $sql2.=" from ".$tabName." as p ";
        $sql2.=" left join crm_company_user as u on u.id=p.parent_id";
        $sql2.=" left join crm_".$tabName1." as z on z.id=p.company_parent_id";
        $sql2.=" left join crm_zsqudao as q on q.id=p.channel_id";
        $sql2.=" LEFT JOIN (SELECT max(update_time),label,person_id,label_type FROM crm_company_user_label WHERE label_type=2 group by person_id) AS l ON l.person_id=p.person_id";
        $sql2.=" left join crm_company_user_order as o on o.user_id=p.id and o.exhibition_id=".$exhibition_id;
        $sql2.=" where 1=1 $param";
        $sql2.=" order by p.id desc";
        $sql2.=" limit ".(($page-1)*$pageSize).",".$pageSize;
        $list=Db::query($sql2);
//        var_dump($list[0]['id_side']);die();
        $columns=$this->baseExcel();
        if($excelType == 2){
            foreach ($list as &$v){
                $v['is_beforehand_name']=$v['group_invitation_type'] == 2?($v['is_beforehand']==2?'预登记报名':'活动报名'):'组团观众';
                $v['status_name']=$v['status']==4?'已完善':'未完善';
                $v['is_push_name']=$v['is_push']==1?'已推送':'未推送';
                $v['is_major_name']=$v['is_major']>0?($v['is_major']==1?'专业观众':'普通观众'):'';
                $v['order_status_name']=$v['is_major']>0?($v['order_status']==1?'已支付':'未支付'):'';
                if($excelType == 2){
                    $question1=json_decode($v['question'],true);
                    $question2=json_decode($v['question1'],true);
                    $question1=is_array($question1)?$question1:[];
                    $question2=is_array($question2)?$question2:[];
                    $userAnser=array_merge($question1, $question2);
                    if(is_array($userAnser) && count($userAnser)>0){
                        $childNum=1;
                        foreach($userAnser as &$ua){
                            $v['answer'.$childNum]=is_array($ua['answer'])?implode(' ',$ua['answer']):(string)$ua['answer'];
                            $childNum++;
                        }
                    }
                }
            }

            $sql="select w.*";
            $sql.=" from crm_zs_question_wenda as w where 1=1 and w.question_is_del=0 and w.exhibition_id=$exhibition_id ";
            $sql.=" order by w.question_category,w.question_sort ";
            $question=Db::query($sql);
            $num=1;
            $litter=['U','V','W','X','Y','Z'];
            foreach ($question as &$vv){
                $obj=array('title' => $vv['question_content'], 'field' => 'answer'.$num, 'width' => 12,'code'=>$litter);
                $columns[]=$obj;
                $num++;
            }
            unset($vv);
        }else{
            foreach ($list as &$v){
                $v['is_beforehand_name']=$v['group_invitation_type'] == 2?($v['is_beforehand']==2?'预登记报名':'活动报名'):'组团观众';
                $v['status_name']=$v['status']==4?'已完善':'未完善';
                $v['is_push_name']=$v['is_push']==1?'已推送':'未推送';
                $v['is_major_name']=$v['is_major']>0?($v['is_major']==1?'专业观众':'普通观众'):'';
                $v['order_status_name']=$v['is_major']>0?($v['order_status']==1?'已支付':'未支付'):'';
            }
        }
        $title = "观众明细";
        $filename = $title . date('Y-m-d-H-i', time()) . ".xls";
        return json(['code'=>1,'msg'=>'操作成功','data'=>['columns'=>$columns,'filename'=>$filename,'list'=>$list]]);
    }


    //导出基础数据
    public function baseExcel(){
        $columns = array(
            array('title' => 'ID', 'field' => 'id', 'width' => 12,'code'=>'A'),
            array('title' => '姓名', 'field' => 'name_cn', 'width' => 12,'code'=>'B'),
            array('title' => '英文姓名', 'field' => 'name_en', 'width' => 12,'code'=>'C'),
            // array('title' => '称谓', 'field' => 'surname_cn', 'width' => 12),
            // array('title' => 'QQ号', 'field' => 'qq', 'width' => 12),
            // array('title' => '微信OpenID', 'field' => 'wechat', 'width' => 12),
            // array('title' => '观众类别', 'field' => 'member_type', 'width' => 12),
            array('title' => '手机', 'field' => 'mobile_person', 'width' => 12,'code'=>'D'),
            array('title' => '证件类型', 'field' => 'id_positive', 'width' => 12,'code'=>'D'),
            array('title' => '身份证/护照号码', 'field' => 'id_side', 'width' => 12,'code'=>'E'),
            array('title' => '电子邮件', 'field' => 'email', 'width' => 12,'code'=>'F'),
            // array('title' => '电话', 'field' => 'tel', 'width' => 12),
            // array('title' => '传真', 'field' => 'fax_person', 'width' => 12),
            //array('title' => '国籍', 'field' => 'country_name', 'width' => 12,'code'=>'G'),
            array('title' => '国家', 'field' => 'country', 'width' => 12,'code'=>'H'),
            array('title' => '省份', 'field' => 'province', 'width' => 24,'code'=>'I'),
            array('title' => '城市', 'field' => 'area_city', 'width' => 24,'code'=>'J'),
            array('title' => '详细地址', 'field' => 'area', 'width' => 24,'code'=>'K'),
            //array('title' => '英文地址', 'field' => 'area_en', 'width' => 24),
            array('title' => '公司名称', 'field' => 'company_name', 'width' => 12,'code'=>'L'),
            array('title' => '公司名称英文', 'field' => 'company_name_en', 'width' => 12),
            array('title' => '行业', 'field' => 'industrys', 'width' => 24,'code'=>'M'),
            array('title' => '部门', 'field' => 'department_cn', 'width' => 24,'code'=>'N'),
            array('title' => '职位', 'field' => 'positions_cn', 'width' => 24,'code'=>'O'),
            // array('title' => '数据来源', 'field' => 'user_form_data', 'width' => 24),
            array('title' => '卡号', 'field' => 'is_cart', 'width' => 24,'code'=>'P'),
            // array('title' => '邀请码', 'field' => 'registration_no', 'width' => 24),
            array('title' => '邀请展商', 'field' => 'company_name_parent', 'width' => 24,'code'=>'Q'),
            array('title' => '邀请人', 'field' => 'parent_name', 'width' => 24,'code'=>'R'),
            array('title' => '渠道', 'field' => 'title', 'width' => 24,'code'=>'S'),
            array('title' => '注册时间', 'field' => 'create_time', 'width' => 24,'code'=>'T'),
            // array('title' => '邀请人类型', 'field' => 'qd_type', 'width' => 24),
            // array('title' => '备注', 'field' => 'no_info', 'width' => 24),'S','T'
            // array('title' => '是否支付会议款项', 'field' => 'no_info', 'width' => 24),
            // array('title' => '负责人', 'field' => 'no_info', 'width' => 24),
            // array('title' => 'E展通注册方式', 'field' => 'no_info', 'width' => 24),
            // array('title' => '支付金额', 'field' => 'no_info', 'width' => 24),
            // array('title' => '预登记邀请', 'field' => 'examine_type_str', 'width' => 24),
            // array('title' => '参加活动', 'field' => 'examine_type_str', 'width' => 24),
            // array('title' => '登录密码', 'field' => '', 'width' => 24),
            // array('title' => '邮编', 'field' => '', 'width' => 24),
            array('title' => '推送', 'field' => 'is_push_name', 'width' => 24),
            array('title' => '报名类型', 'field' => 'is_beforehand_name', 'width' => 24),
            array('title' => '是否老观众', 'field' => 'label_titles', 'width' => 24),
            array('title' => '信息完善', 'field' => 'status_name', 'width' => 24),
            array('title' => '观众类型', 'field' => 'is_major_name', 'width' => 24),
            array('title' => '支付状态', 'field' => 'order_status_name', 'width' => 24),
            array('title' => '审核', 'field' => 'examine_type', 'width' => 24),
            // array('title' => '审核', 'field' => 'examine_type_str', 'width' => 24),
        );

        return $columns;
    }




    public function setPerson(){
        $exhibition_id =$this->request->param('exhibition_id');
        $tabNames=$this->getTabName($exhibition_id);
        $list=db($tabNames)->field('id')->where(['back'=>0])->select();
        if(!empty($list)){
            $ids=[];
            foreach ($list as &$v) {
                $ids[]=$v['id'];
            }
            $fWhere['id'] = array('in',implode(',',$ids));
            $fRes=db($tabNames)->where($fWhere)->update(['back'=>1]);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }


    public function saveExcel(){
        $filename=$this->request->param('filename');
        $exhibition_id =$this->request->param('exhibition_id');
        if(empty($filename)){
            return json(['code'=>0,'msg'=>'excel缺失，请重新上传','data'=>'']);
        }
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $filename = ROOT_PATH.'public/uploads/excel/'.$filename;
        $reader = PHPExcel_IOFactory::createReaderForFile($filename);
        $excel = $reader->load($filename, $encode = 'utf-8');
        $excel_array=$excel->getsheet(0)->toArray();  //转换为数组格式
        $list=array();
        array_shift($excel_array);  //删除第一个数组(标题);
        if (!is_array($excel_array) || empty($excel_array) || count($excel_array)==0) {
            return json(['code' => 0, 'msg' => '获取数据失败！']);
        } else {
            $time=time();
            foreach ($excel_array as $key => $value) {
                if($value[2]>0){
                    $list[$key]['name_cn'] = trim((string) $value[0], chr(0xc2) . chr(0xa0));//中文姓名
                    $list[$key]['name_en'] = trim((string) $value[1], chr(0xc2) . chr(0xa0)); //英文姓名
                    $list[$key]['mobile_person'] = trim((string) $value[2], chr(0xc2) . chr(0xa0)); //电话
                    $list[$key]['email'] = trim((string) $value[3], chr(0xc2) . chr(0xa0)); // 邮件
                    $list[$key]['country'] = trim((string) $value[4], chr(0xc2) . chr(0xa0)); // 国家
                    $list[$key]['province'] = trim((string) $value[5], chr(0xc2) . chr(0xa0)); // 省份
                    $list[$key]['area_city'] = trim((string) $value[6], chr(0xc2) . chr(0xa0)); // 城市
                    $list[$key]['area'] = trim((string) $value[7], chr(0xc2) . chr(0xa0)); // 详细地址
                    $list[$key]['company_name'] = trim((string)$value[8], chr(0xc2) . chr(0xa0)); // 公司名称
                    $list[$key]['company_name_en'] = trim((string)$value[9], chr(0xc2) . chr(0xa0)); // 英文名称
                    $list[$key]['industrys'] = trim((string)$value[10], chr(0xc2) . chr(0xa0)); // 行业
                    $list[$key]['department_cn'] = trim((string)$value[11], chr(0xc2) . chr(0xa0)); // 部门
                    $list[$key]['positions_cn'] = trim((string)$value[12], chr(0xc2) . chr(0xa0)); // 职位
                    $list[$key]['is_cart'] = trim((string)$value[13], chr(0xc2) . chr(0xa0)); // 卡号
                    $list[$key]['category_id'] = trim((string)$value[14], chr(0xc2) . chr(0xa0)); // 一级分类
                    $list[$key]['second_category_id'] = trim((string)$value[15], chr(0xc2) . chr(0xa0)); // 二级分类
                    $list[$key]['id_side'] = trim((string)$value[16], chr(0xc2) . chr(0xa0)); // 身份证号码
                    $list[$key]['id_positive'] = trim((string)$value[17], chr(0xc2) . chr(0xa0)); // 身份证类型
                    $list[$key]['channel_id'] = trim((string)$value[18], chr(0xc2) . chr(0xa0)); // 渠道
                    $list[$key]['group_invitation_type'] = trim((string)$value[19], chr(0xc2) . chr(0xa0)); // 是否组团
                    $list[$key]['status']=trim((string)$value[20], chr(0xc2) . chr(0xa0));
                    $list[$key]['create_time']=$time;
                    $list[$key]['update_time']=$time;
                    $list[$key]['examine_type']=1;
                    $list[$key]['is_beforehand']=1;
                }
            }
            if(count($list)>1000){
                return json(['code' => 0, 'msg' => '数据请控制在1000条以内！']);
            }
            //开始进入临时表
            $clearSQL="truncate table crm_person_temporary";
            Db::query($clearSQL);
            $result=db('person_temporary')->insertAll($list);
            if(!$result){
                return json(['code'=>0,'msg'=>'临时插入失败']);
            }
            //根据基础表更新临时表id
            $upSql=" select l.mobile_person,b.id from crm_person_temporary as l ";
            $upSql.=" left join crm_company_user as b on b.mobile_person=l.mobile_person ";
            $upRes=Db::query($upSql);
            $phone=array();
            foreach ($upRes as &$v){
                if($v['id']==null || empty($v['id']) || $v['id']==''){
                    $phone[]=$v['mobile_person'];
                }
            }

            if(count($phone)>0){
                $basesql="select name_cn,name_en,mobile_person,email,country,province,area_city,area,company_name,industrys,department_cn,positions_cn,category_id,second_category_id,create_time,update_time from crm_person_temporary where mobile_person in (".implode(',', $phone).")";
//                var_dump($basesql);die();
                $baseList=Db::query($basesql);
                if(count($baseList)>0){
                    $resBase=db('company_user')->insertAll($baseList);
                    if(!$resBase){
                        return json(['code'=>0,'msg'=>'基础表插入失败']);
                    }
                }
            }

            //查重展商表
            $zsSql=" select l.mobile_person,b.id from crm_person_temporary as l ";
            $zsSql.=" left join crm_".$tabName." as b on b.mobile_person=l.mobile_person ";
            $zsRes=Db::query($zsSql);
            $zsArr=array();
            foreach ($zsRes as &$v){
                if($v['id']!=null || !empty($v['id']) || $v['id']!=''){
                    $zsArr[]=$v['mobile_person'];
                }
            }

            $sql=" select l.name_cn,l.name_en,l.mobile_person,l.email,l.country,l.province,l.area_city,l.area,l.company_name,l.industrys,l.department_cn,l.positions_cn,l.category_id,l.second_category_id,l.create_time,l.update_time,l.is_cart,id_side,l.id_positive,l.channel_id,l.group_invitation_type,l.status,l.examine_type,l.is_beforehand,b.id as person_id from crm_person_temporary as l ";
            $sql.=" left join crm_company_user as b on b.mobile_person=l.mobile_person ";
            if(count($zsArr)>0){
                $sql.=" where l.mobile_person not in (".implode(',', $zsArr).")";
            }
            $isAll=Db::query($sql);
            if(count($isAll)>0){
                $resGz=db($tabName)->insertAll($isAll);
                if(!$resGz){
                    return json(['code'=>0,'msg'=>'观众表插入失败']);
                }
            }

            return json(['code' => 1, 'msg' => '操作成功']);
        }
    }


    //获取观众详细信息
    public function getUserDetail(){
        $id=$this->request->param('id');//企业库人员id
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>1,'msg'=>'展会信息错误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        };
        $tabName=$this->getTabName($exhibition_id);
        $result=db($tabName)->where(['id'=>$id])->find();
        return json(['code'=>1,'msg'=>'请求成功','data'=>$result]);
    }


    //获取问卷调查数据
    public function getQuestion(){
        $exhibition_id = $this->request->param('exhibition_id');
        $type = $this->request->param('type');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $param=" and w.question_is_del=0 and w.exhibition_id=$exhibition_id ";
        if(!empty($type)){
            $param.=" and question_category=$type ";
        }
        $sql2="select w.*,c.id as exhibition_id,c.title ";
        $sql2.=" from crm_zs_question_wenda as w LEFT JOIN crm_exhibition as c ON w.exhibition_id=c.id where 1=1 $param";
        $sql2.=" order by w.question_category,w.question_sort ";
        $list=Db::query($sql2);
        if(!$list){
            return json(['code'=>0,'msg'=>'题库查询错误']);
        }
        foreach ($list as &$v){
            $v['question_content_sel']=json_decode($v['question_content_sel'],true);
        }
        unset($v);
        return json(['code'=>1,'msg'=>'操作成功','data'=>$list]);

    }


    //获取推荐人
    public function recommendList(){
        $id=$this->request->param('id');//人员id
        if(empty($id)){
            return json(['code'=>0,'msg'=>'主键错误']);
        }
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $list=db($tabName)->where(['parent_id'=>$id])->select();
        return json(['code'=>1,'msg'=>'操作成功','data'=>$list]);
    }

    //保存基础信息
    public function save(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $page_active=$this->request->param('page_active');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $info=db($tabName)->where(['id'=>$id])->find();
        if(empty($info)){
            return json(['code'=>0,'msg'=>'观众信息错误']);
        }
        $data=array();
        if($page_active == 1){
            $name_cn=$this->request->param('name_cn');
            $area=$this->request->param('area');
            $mobile_person=$this->request->param('mobile_person');
            $email=$this->request->param('email');
            $country=$this->request->param('country');
            $province=$this->request->param('province');
            $area_city=$this->request->param('area_city');
            $company_name=$this->request->param('company_name');
            $company_name_en=$this->request->param('company_name_en');
            $industrys=$this->request->param('industrys');
            $department_cn=$this->request->param('department_cn');
            $positions_cn=$this->request->param('positions_cn');
            $is_person=$this->request->param('is_person');
            $data=array();
            if(!empty($name_cn)){
                $data['name_cn']=$name_cn;
            }
            if(!empty($area)){
                $data['area']=$area;
            }
            if(!empty($mobile_person)){
                $data['mobile_person']=$mobile_person;
            }
            if(!empty($email)){
                $data['email']=$email;
            }
            if(!empty($country)){
                $data['country']=$country;
            }
            if(!empty($email)){
                $data['email']=$email;
            }
            if(!empty($province)){
                $data['province']=$province;
            }
            if(!empty($area_city)){
                $data['area_city']=$area_city;
            }
            if(!empty($company_name)){
                $data['company_name']=$company_name;
            }
            if(!empty($company_name_en)){
                $data['company_name_en']=$company_name_en;
            }
            if(!empty($industrys)){
                $data['industrys']=$industrys;
            }
            if(!empty($department_cn)){
                $data['department_cn']=$department_cn;
            }
            if(!empty($positions_cn)){
                $data['positions_cn']=$positions_cn;
            }
        }else if($page_active == 2){
            $question=$this->request->param('question');//问卷调查
            if(!empty($question)){
                $data['question']=$question;
            }
        }else if($page_active == 3){
            $id_positive=$this->request->param('id_positive');//身份证正面
            $id_side=$this->request->param('id_side');//身份证反面
            $name_cn=$this->request->param('name_cn');//姓名
            if(!empty($id_positive)){
                $data['id_positive']=$id_positive;
            }
            if(!empty($id_side)){
                $data['id_side']=$id_side;
            }
            if(!empty($name_cn)){
                $data['name_cn']=$name_cn;
            }
        }else if($page_active == 4){
            $data['status']=$this->request->param('status');
        }

        $result=db($tabName)->where(['id'=>$id])->update($data);
        if(!$result){
            return json(['code'=>0,'msg'=>'修改失败']);
        }
        if($page_active == 1){
            db('company_user')->where(['id'=>$info['person_id']])->update($data);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
        
    }

    //保存身份证
    public function saveIds(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $info=db($tabName)->where(['id'=>$id])->find();
        if(empty($info)){
            return json(['code'=>0,'msg'=>'观众信息错误']);
        }
        $id_positive=$this->request->param('id_positive');
        $id_side=$this->request->param('id_side');
        if(empty($id_positive) || empty($id_side)){
            return json(['code'=>0,'msg'=>'数据未填写']);
        }
        $data['id_positive']=$id_positive;
        $data['id_side']=$id_side;
        $result=db($tabName)->where(['id'=>$id])->update($data);
        if(!$result){
            return json(['code'=>0,'msg'=>'修改失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }


    public function pushExhibition(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $info=db($tabName)->where(['id'=>$id])->find();
        $res=$this->pushCrul($info,$exhibition_id);
        if($res['code'] == 1){
            $cPer=db($tabName)->where(['id'=>$id])->update(['is_push'=>1]);
            if(!$cPer){
                return json(['code'=>0,'msg'=>'推送失败']);
            }
            return json(['code'=>1,'msg'=>'推送成功']);
        }else{
            return json(['code'=>0,'msg'=>$res['msg']]);
        }
    }


    public function addbuyerlist(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        if(!$id){
            return json(['code'=>0,'msg'=>'请选择一个观众!']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $cPer=db($tabName)->where(['id'=>array('in',$id)])->update(['label'=>1]);
        if(!$cPer){
            return json(['code'=>0,'msg'=>'操作失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }



    public function removebuyerlist(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        if(!$id){
            return json(['code'=>0,'msg'=>'请选择一个观众!']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $cPer=db($tabName)->where(['id'=>array('in',$id)])->update(['label'=>null]);
        if(!$cPer){
            return json(['code'=>0,'msg'=>'操作失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }



    public function buyerlist(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $exhibition_id=$this->request->param('exhibition_id');
        $keyWord=$this->request->param('keyword');
        $phone=$this->request->param('phone');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $where['label']=1;
        if($keyWord){
            $where['name_cn']=array('like',"'%'$keyWord'%'");
        }
        if($phone){
            $where['mobile_person']=array('like',"'%'$phone'%'");
        }
        $where['is_delete']=0;
        $tabName=$this->getTabName($exhibition_id);
        $cPer=db($tabName)->where($where)->limit(($page-1)*$pagesize.','.$pagesize)->select();
        foreach ($cPer as &$v){
            $v['mobile_person']=$v['mobile_person']?substr_replace($v['mobile_person'], '****', 3, 4):'';
        }
        $count=db($tabName)->where($where)->count();
        return json(['code'=>1,'msg'=>'操作成功','data'=>['list'=>$cPer,'count'=>$count,'exhibition_name'=>$exhibition['title']]]);
    }

    //推送请求
    public function pushCrul($data,$exhibition_id){
        $param["Name"]=$data['name_cn']."";	//选填	string	姓名
        $param["ComName"]=$data['company_name']."";	//选填	string	公司名称
        $param["CardType"]='观众';	//选填	String	证件类型（身份证、港澳通行证、护照）
        $param["IDCardType"]=$data['id_positive']."";	//选填	String	证件类型（身份证、港澳通行证、护照）
        $param["Mobile"]=$data['mobile_person']."";	//选填	string	手机号
        $param["Email"]=$data['email']."";	//选填	string	邮箱
        $param["CardNo"] = $data['is_cart'].""; //卡号
        $param["Title"]=$data['positions_cn']."";	//选填	string	职务
        $param["Dept"]=$data['department_cn']."";	//选填	string	部门
        $param["Country"]=$data['country']."";	//选填	string	国家/地区
        $param["Province"]=$data['province']."";	//选填	string	省份
        $param["City"]=$data['area_city']."";	//选填	string	城市
        $param["IdCard"]=$data['id_side']."";	//选填	string	身份证号
        $param["Remark"]='';	//选填	string	备注
//        var_dump($param);die();
        $postData=array(
            "exhid"=>"RaIRHa6", 
            "data"=>json_encode(array($param))
        );
        $host = "http://api.exporegist.com/common";//正式
//        $host = "http://api.exporegist.com/commonTest";//测试
        $url=$host.'/api/scene/synccard';
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $headers = array();
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type: multipart/form-data;");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        $result = curl_exec($ch);
//        var_dump($result);die();
        curl_close($ch);
        if($result){
            $result=json_decode($result,true);
            if($result['status']=='1'){
                return array('code'=>1,'msg'=>'推送成功');
            }else{
                return array('code'=>0,'msg'=>$result['ErrorMsg']);
            }
        }else{
            return array('code'=>0,'msg'=>'请求失败');
        }
    }

    public function delete(){
        $id=$this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $info=db($tabName)->where(['id'=>$id])->find();
        if(!$info){
            return json(['code'=>0,'msg'=>'数据错误']);
        }
        $res=db($tabName)->where(['id'=>$id])->delete();
        if(!$res){
            return json(['code'=>0,'msg'=>'删除失败']);
        }
        return json(['code'=>1,'msg'=>'成功']);
    }


    /**
     * 观众列表
     * @param member_id,public_id,sale_id
     */
    public function billingIndex(){
        if (request()->isPost()) {
            $post = input('post.');
            $page = isset($post['page']) && $post['page'] != '' ? $post['page'] : 1;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $keyWord = isset($post['keyWord']) && $post['keyWord'] != '' ? $post['keyWord'] : null;
            $phone = isset($post['phone']) && $post['phone'] != '' ? $post['phone'] : null;
            $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $param=" and o.exhibition_id=".$exhibition_id." and o.is_delete=0 and o.status=1";
            //1 未开票 2 未提交 3 已提交 4 已开票
            if($status == 1){
                $param.=" and o.user_id not in (SELECT user_id FROM crm_companyuser_billing WHERE is_delete=0 AND exhibition_id=".$exhibition_id.")";
            }else if($status == 2){
                $param.=" and o.user_id in (SELECT user_id FROM crm_companyuser_billing WHERE is_delete=0 AND exhibition_id=".$exhibition_id." and billing_status=0)";
            }else if($status == 3){
                $param.=" and o.user_id in (SELECT user_id FROM crm_companyuser_billing WHERE is_delete=0 AND exhibition_id=".$exhibition_id." and billing_status=1)";
            }else if($status == 4){
                $param.=" and o.user_id in (SELECT user_id FROM crm_companyuser_billing WHERE is_delete=0 AND exhibition_id=".$exhibition_id." and billing_status=2)";
            }
            if($keyWord){
                $param.=" and u.name_cn LIKE '%$keyWord%' or u.company_name LIKE '%$keyWord%' ";
            }
            if($phone){
                $param.=" and u.mobile_person LIKE '%$keyWord%' ";
            }
            $sql="SELECT o.wx_order_num,o.total_fee,o.play_time,u.name_cn,u.id as user_id,u.company_name,u.mobile_person,u.is_major,kp.bill_id,kp.billing_status,kp.submit_time,kp.billing_time FROM crm_company_user_order as o ";
            $sql.=" LEFT JOIN crm_".$tabName." as u ON u.id=o.user_id";
            $sql.=" LEFT JOIN (SELECT max(id) as bill_id,billing_status,submit_time,user_id,billing_time FROM crm_companyuser_billing WHERE is_delete=0 AND exhibition_id=".$exhibition_id." GROUP BY user_id ) AS kp ON kp.user_id=o.user_id";
            $sql.=" where 1=1 $param";
            $sql.=" order by o.play_time desc";
            $total1=Db::query($sql);
            $sql.=" limit ".($page-1)*$pageSize.",$pageSize";
            $list=Db::query($sql);
            $total=count($total1); //st
            return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 开票记录详情
     */

    public function billingGetEdit(){
        $post = input('post.');
        $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
        $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
        if (!$exhibition_id) {
            return json(array('code' => '0', 'msg' => '展会信息错误为空'));
        }
        if(!$id){
            return json(['code'=>0,'msg'=>'开票数据错误']);
        }
        $comRes=db('companyuser_billing')->where(['id'=>$id,'is_delete'=>0])->find();
        return json(array('code' => '1', 'msg' => '操作成功','data'=>$comRes));
    }

    /**
     * 添加开票记录
     */

    public function billingAddOrEdit(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
                $user_id = isset($post['user_id']) && $post['user_id'] != '' ? $post['user_id'] : null;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
                $billing_type = isset($post['billing_type']) && $post['billing_type'] != '' ? $post['billing_type'] : 1;
                $tax_number = isset($post['tax_number']) && $post['tax_number'] != '' ? $post['tax_number'] : '';
                $bank_title = isset($post['bank_title']) && $post['bank_title'] != '' ? $post['bank_title'] : '';
                $bank_number = isset($post['bank_number']) && $post['bank_number'] != '' ? $post['bank_number'] : '';
                $company_phone = isset($post['company_phone']) && $post['company_phone'] != '' ? $post['company_phone'] : '';
                $company_name = isset($post['company_name']) && $post['company_name'] != '' ? $post['company_name'] : '';
                $company_address = isset($post['company_address']) && $post['company_address'] != '' ? $post['company_address'] : '';
                $billing_mode = isset($post['billing_mode']) && $post['billing_mode'] != '' ? $post['billing_mode'] : 1;
                $billing_money = isset($post['billing_money']) && $post['billing_money'] != '' ? $post['billing_money'] : '';
                $receiving_name = isset($post['receiving_name']) && $post['receiving_name'] != '' ? $post['receiving_name'] : '';
                $receiving_phone = isset($post['receiving_phone']) && $post['receiving_phone'] != '' ? $post['receiving_phone'] : '';
                $receiving_address = isset($post['receiving_address']) && $post['receiving_address'] != '' ? $post['receiving_address'] : '';
                if (!$exhibition_id) {
                    return json(array('code' => '0', 'msg' => '展会信息错误为空'));
                }
                $tabName=$this->getTabName($exhibition_id);
                $comRes=db($tabName)->where(['id'=>$user_id])->find();
                if(!$comRes){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }

                $data['exhibition_id']=$exhibition_id;
                $data['user_id']=$user_id;
                $data['billing_type']=$billing_type;
                $data['tax_number']=$tax_number;
                $data['bank_title']=$bank_title;
                $data['bank_number']=$bank_number;
                $data['company_phone']=$company_phone;
                $data['company_address']=$company_address;
                $data['billing_mode']=$billing_mode;
                $data['billing_money']=$billing_money;
                $data['receiving_name']=$receiving_name;
                $data['company_name']=$company_name;
                $data['receiving_phone']=$receiving_phone;
                $data['receiving_address']=$receiving_address;
                $data['create_time']=time();
                $data['update_time']=time();
                $data['member_id']=$admin['id'];
                $res='';
                if($id){
                    $search=db('companyuser_billing')->where(['id'=>$id])->find();
                    if(!$search){
                        return json(array('code' => '0', 'msg' => '数据错误'));
                    }
                    if($search['billing_status'] == 2){
                        return json(array('code' => '0', 'msg' => '财务已开票，无法此操作'));
                    }
                    $res=db('companyuser_billing')->where(['id'=>$id])->update($data);
                    if(false===$res){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }else{
                    $res=db('companyuser_billing')->insert($data);
                    if(false===$res){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function billingUpload(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $search=db('companyuser_billing')->where(['id'=>$id])->find();
                if(!$search){
                    return json(array('code' => '0', 'msg' => '数据错误'));
                }
                if($search['billing_status'] == 1){
                    return json(array('code' => '0', 'msg' => '已申请，请勿重复操作'));
                }
                if($search['billing_status'] == 2){
                    return json(array('code' => '0', 'msg' => '已开票，无法此操作'));
                }
                $res=db('companyuser_billing')->where(['id'=>$id])->update(['billing_status'=>1,'submit_time'=>time()]);
                if(false==$res){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function billingDelete(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $search=db('companyuser_billing')->where(['id'=>$id])->find();
                if(!$search){
                    return json(array('code' => '0', 'msg' => '数据错误'));
                }
                if($search['billing_status'] == 2){
                    return json(array('code' => '0', 'msg' => '已开票，无法此操作'));
                }
                $res=db('companyuser_billing')->where(['id'=>$id])->update(['is_delete'=>1]);
                if(false==$res){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


}